package cn.iocoder.yudao.module.system.service.gugu;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ProvinceScoreInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ProvinceScoreQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ProvinceScorePageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.ProvinceScoreDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.ProvinceScoreMapper;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历年高考省录取分数线数据 Service 实现类
 */
@Service
@Slf4j
public class ProvinceScoreServiceImpl implements ProvinceScoreService {

    @Resource
    private ProvinceScoreMapper provinceScoreMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveProvinceScoreList(List<ProvinceScoreInfo> provinceScoreList) {
        if (provinceScoreList == null || provinceScoreList.isEmpty()) {
            return 0;
        }

        int savedCount = 0;
        for (ProvinceScoreInfo info : provinceScoreList) {
            // 检查是否已存在相同的记录
            boolean exists = existsProvinceScore(info.getProvince(), info.getYear(), 
                    info.getCategory(), info.getScoreBatch());
            
            if (!exists) {
                ProvinceScoreDO provincScore = ProvinceScoreDO.builder()
                        .province(info.getProvince())
                        .category(info.getCategory())
                        .scoreBatch(info.getScoreBatch())
                        .year(info.getYear())
                        .score(info.getScore())
                        .specialName(info.getSpecialName())
                        .build();
                
                provinceScoreMapper.insert(provincScore);
                savedCount++;
            } else {
                log.debug("省录取分数线数据已存在，跳过保存: 省份={}, 年份={}, 学科分类={}, 录取批次={}", 
                        info.getProvince(), info.getYear(), info.getCategory(), info.getScoreBatch());
            }
        }

        return savedCount;
    }

    @Override
    public List<ProvinceScoreDO> getProvinceScoreList(String province, Integer year, String category) {
        return provinceScoreMapper.selectByProvinceYearAndCategory(province, year, category);
    }

    @Override
    public List<ProvinceScoreDO> getProvinceScoreByProvince(String province) {
        return provinceScoreMapper.selectByProvince(province);
    }

    @Override
    public List<ProvinceScoreDO> getProvinceScoreByYear(Integer year) {
        return provinceScoreMapper.selectByYear(year);
    }

    @Override
    public List<ProvinceScoreDO> getProvinceScoreByCategory(String category) {
        return provinceScoreMapper.selectByCategory(category);
    }

    @Override
    public PageResult<ProvinceScoreDO> getProvinceScorePage(ProvinceScorePageReqVO reqVO) {
        return provinceScoreMapper.selectPage(reqVO);
    }

    @Override
    public boolean existsProvinceScore(String province, Integer year, String category, String scoreBatch) {
        return provinceScoreMapper.existsByProvinceYearCategoryAndBatch(province, year, category, scoreBatch);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> fetchAndSaveProvinceScore(String appkey, String keyword, Integer year, String category) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证appkey是否有效
            if (!GuGuDataUtils.validateProvinceScoreApiKey(appkey)) {
                result.put("success", false);
                result.put("message", "无效的APPKEY");
                return result;
            }

            // 构建请求参数
            ProvinceScoreQueryReqVO reqVO = new ProvinceScoreQueryReqVO();
            reqVO.setKeyword(keyword);
            reqVO.setYear(year);
            reqVO.setCategory(category);

            // 调用API获取数据
            Map<String, Object> apiResult = GuGuDataUtils.getProvinceScoreInfo(reqVO);

            if (!Boolean.TRUE.equals(apiResult.get("success"))) {
                result.put("success", false);
                result.put("message", "API调用失败: " + apiResult.get("message"));
                return result;
            }

            @SuppressWarnings("unchecked")
            List<ProvinceScoreInfo> provinceScoreList = (List<ProvinceScoreInfo>) apiResult.get("provinceScoreList");

            if (provinceScoreList == null || provinceScoreList.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有获取到省录取分数线数据");
                result.put("savedCount", 0);
                result.put("totalCount", 0);
                return result;
            }

            // 保存到数据库
            int savedCount = saveProvinceScoreList(provinceScoreList);

            result.put("success", true);
            result.put("message", "成功获取并保存省录取分数线数据");
            result.put("savedCount", savedCount);
            result.put("totalCount", provinceScoreList.size());
            result.put("apiTotalCount", apiResult.get("totalCount"));

            return result;
        } catch (Exception e) {
            log.error("获取并保存省录取分数线数据失败", e);
            result.put("success", false);
            result.put("message", "获取并保存省录取分数线数据失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProvinceScore(String province, Integer year, String category, String scoreBatch) {
        return provinceScoreMapper.deleteByProvinceYearCategoryAndBatch(province, year, category, scoreBatch);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProvinceScoreByYear(Integer year) {
        return provinceScoreMapper.deleteByYear(year);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProvinceScore(ProvinceScoreDO createReqVO) {
        // 插入
        provinceScoreMapper.insert(createReqVO);
        // 返回
        return createReqVO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProvinceScore(ProvinceScoreDO updateReqVO) {
        // 校验存在
        validateProvinceScoreExists(updateReqVO.getId());
        // 更新
        provinceScoreMapper.updateById(updateReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProvinceScore(Long id) {
        // 校验存在
        validateProvinceScoreExists(id);
        // 删除
        provinceScoreMapper.deleteById(id);
    }

    private void validateProvinceScoreExists(Long id) {
        if (provinceScoreMapper.selectById(id) == null) {
            throw new RuntimeException("省录取分数线数据不存在");
        }
    }

    @Override
    public ProvinceScoreDO getProvinceScore(Long id) {
        return provinceScoreMapper.selectById(id);
    }
}
